#include "stdafx.h"

#include "settings_editor.h"
#include "parameter_editor.h"
#include "units.h"

using namespace std;

settingsEditor::settingsEditor(QWidget* pwgt) 
	: QDialog(pwgt, Qt::WindowTitleHint | Qt::WindowSystemMenuHint)
{
	ui.setupUi(this);
	connect(ui.btnAccept, SIGNAL(clicked), this, SLOT(on_btnAccept_clicked));
	connect(ui.btnReject, SIGNAL(clicked), this, SLOT(on_btnReject_clicked));
	ui.table->setStyleSheet("alternate-background-color: rgb(190, 234, 235)");
	ui.table->setItemDelegate(new LineEditDelegate);
	ui.table->setColumnWidth(0, 170);
}

settingsEditor::~settingsEditor(){
	
}

void settingsEditor::on_btnAccept_clicked(){
	accept();
}

void settingsEditor::on_btnReject_clicked(){
	int result = QMessageBox::information(this, "Close", 
		"Close the form? any unsaved data will be lost", 
		QMessageBox::Yes | QMessageBox::Default, 
		QMessageBox::No, 
		QMessageBox::Cancel | QMessageBox::Escape); 
	if (result == QMessageBox::Yes) 
		reject();
}

void settingsEditor::setUnits(const hash_map<string, int> &_defaultUnits){
	ui.table->clear();
	parameter.clear();
	unit.clear();
	ui.table->setRowCount(_defaultUnits.size());
	int index = 0;
	Units *unitlist = new Units();
	for (hash_map<string, int>::const_iterator it = _defaultUnits.begin(); it != _defaultUnits.end(); it++) {
		QTableWidgetItem *p = new QTableWidgetItem;
		p->setData(Qt::EditRole, QString::fromStdString(it->first));
		parameter.push_back(p);
		ui.table->setItem(index, 0, p);
		QComboBox *u = new QComboBox;
		QStringList units = unitlist->getUnitListForParameter(QString::fromStdString(it->first));
		for (int i = 0; i < units.size(); i++)
			u->addItem(units[i]);
		if (u->count() >= it->second) u->setCurrentIndex(it->second);
		unit.push_back(u);
		ui.table->setCellWidget(index++, 1, u);
	}
}

hash_map<string, int> settingsEditor::getUnits(){
	hash_map<string, int> _defaultUnits;
	for(int i = 0; i < parameter.size(); i++){
		QString name = parameter[i]->data(0).toString();
		int index = unit[i]->currentIndex();
		_defaultUnits[name.toStdString()] = index;
	}
	return _defaultUnits;
}